<?php

namespace app\api\controller\task;

use app\common\controller\Api;
use think\Db;

class Cron extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    /**
     * @var \app\common\model\meet\Cron
     */
    protected $model = null;

    /**
     * @var \app\common\logic\meet\Cron
     */
    protected $logic = null;

    public function _initialize()
    {
        parent::_initialize();

        // 清除错误
        error_reporting(0);

        // 设置永不超时
        set_time_limit(0);

        $this->model = new \app\common\model\meet\Cron();

        $this->logic = new \app\common\logic\meet\Cron();
    }

    public function index()
    {
        $list = $this->model->where('execute_time', 'elt', time())->where(['execute_time' => ['elt', time()], 'status' => $this->model::STATUS_WAIT])->select();

        if ($list) {
            foreach ($list as $key => $value) {
                Db::startTrans();
                try {
                    $value->save(['status' => $this->model::STATUS_IN]);

                    switch ($value['event']) {
                        case 'CronMallOrderCancel': //商城-取消订单
                            $this->logic->orderCancel($value['relate_id']);
                            break;
                        case 'CronMallOrderComplete': //商城-订单完成
                            $this->logic->orderComplete($value['relate_id']);
                            break;
                        case 'CronMallOrderMessage': //商城-下单成功发送消息
                            $this->logic->orderSendMessage($value['relate_id']);
                            break;
                        case 'CronMeetOrderCancel': //预约-取消订单
                            $this->logic->meetOrderCancel($value['relate_id']);
                            break;
//                        case 'CronMeetOrderComplete': //预约-订单完成
//                            $this->logic->meetOrderComplete($value['relate_id']);
//                            break;
                        case 'CronMeetOrderMessage': //预约-下单成功发送消息
                            $this->logic->meetOrderSendMessage($value['relate_id']);
                            break;
                    }

                    $value->delete();
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                }
            }
        }

        $this->success(__('运行成功'));
    }
}